<template>
  <div class="container mx-auto">
    <!-- 页面标题和操作按钮 -->
    <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between">
      <div>
        <p class="text-gray-500 mt-1">管理平台所有用户账号及权限</p>
      </div>
      <button
          class="mt-4 sm:mt-0 px-4 py-2 bg-emerald-600 text-white rounded-md hover:bg-emerald-700 transition-colors flex items-center"
          @click="openAddUserModal"
      >
        <i class="fa fa-plus mr-2"></i> 新增用户
      </button>
    </div>

    <!-- 筛选和搜索 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">用户角色</label>
          <select
              v-model="selectedRole"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
              @change="filterUsers"
          >
            <option value="">全部角色</option>
            <option value="超级管理员">超级管理员</option>
            <option value="厂商管理员">厂商管理员</option>
            <option value="普通用户">普通用户</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">用户状态</label>
          <select
              v-model="selectedStatus"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
              @change="filterUsers"
          >
            <option value="">全部状态</option>
            <option value="active">活跃</option>
            <option value="inactive">已禁用</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">搜索用户</label>
          <div class="relative">
            <input
                type="text"
                placeholder="输入用户名或邮箱..."
                class="pl-10 pr-4 py-2 w-full border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
                v-model="searchKeyword"
                @input="filterUsers"
            >
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white rounded-lg shadow mb-6">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
          <tr>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属厂商</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册日期</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最后登录</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(user, index) in filteredUsers" :key="user.id" class="hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="flex items-center">
                <div class="h-10 w-10 flex-shrink-0">
                  <img class="h-10 w-10 rounded-full" :src="user.avatar" :alt="user.name">
                </div>
                <div class="ml-4">
                  <div class="text-sm font-medium text-gray-900">{{ user.name }}</div>
                  <div class="text-sm text-gray-500">ID: {{ user.id }}</div>
                </div>
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm text-gray-900">{{ user.email }}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="text-sm text-gray-900">{{ user.company || '无' }}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                      :class="user.role === '超级管理员' ? 'bg-purple-100 text-purple-800' :
                         user.role === '厂商管理员' ? 'bg-blue-100 text-blue-800' :
                         'bg-green-100 text-green-800'">
                  {{ user.role }}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              {{ user.regDate }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              {{ user.lastLogin || '未登录' }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="user.active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                >
                  {{ user.active ? '活跃' : '已禁用' }}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
              <button class="text-emerald-600 hover:text-emerald-900 mr-3" @click="openEditUserModal(user)">编辑</button>
              <button class="text-amber-600 hover:text-amber-900 mr-3" @click="resetPassword(user.id)">重置密码</button>
              <button class="text-red-600 hover:text-red-900" @click="toggleUserStatus(index)">
                {{ user.active ? '禁用' : '启用' }}
              </button>
            </td>
          </tr>
          <tr v-if="filteredUsers.length === 0">
            <td colspan="8" class="px-6 py-10 text-center text-gray-500">
              <i class="fa fa-search fa-2x mb-2"></i>
              <p>未找到匹配的用户信息</p>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200 bg-gray-50 flex items-center justify-between">
        <div class="text-sm text-gray-700">
          显示 <span class="font-medium">1</span> 到 <span class="font-medium">{{ Math.min(10, filteredUsers.length) }}</span> 条，共 <span class="font-medium">{{ filteredUsers.length }}</span> 条
        </div>
        <div class="flex space-x-2">
          <button class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50" disabled>上一页</button>
          <button class="px-3 py-1 border border-gray-300 rounded-md text-sm text-white bg-emerald-600 hover:bg-emerald-700">1</button>
          <button class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50">2</button>
          <button class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50">3</button>
          <button class="px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50">下一页</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 新增/编辑用户弹窗 -->
  <div v-if="showUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-gray-800">{{ isEditing ? '编辑用户' : '新增用户' }}</h3>
        <button @click="closeUserModal" class="text-gray-400 hover:text-gray-500">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <form @submit.prevent="saveUser">
        <div class="space-y-4 mb-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">用户名 <span class="text-red-500">*</span></label>
            <input
                type="text"
                v-model="currentUser.name"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
                required
            >
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">邮箱 <span class="text-red-500">*</span></label>
            <input
                type="email"
                v-model="currentUser.email"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
                required
                :disabled="isEditing"
            >
            <p class="text-xs text-gray-500 mt-1" v-if="isEditing">邮箱地址不可修改</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">角色 <span class="text-red-500">*</span></label>
            <select
                v-model="currentUser.role"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
                required
            >
              <option value="">请选择角色</option>
              <option value="超级管理员">超级管理员</option>
              <option value="厂商管理员">厂商管理员</option>
              <option value="普通用户">普通用户</option>
            </select>
          </div>

          <div v-if="currentUser.role === '厂商管理员'">
            <label class="block text-sm font-medium text-gray-700 mb-1">所属厂商</label>
            <select
                v-model="currentUser.company"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
            >
              <option value="">请选择厂商</option>
              <option v-for="company in companies" :key="company.id" :value="company.name">{{ company.name }}</option>
            </select>
          </div>

          <div v-if="!isEditing">
            <label class="block text-sm font-medium text-gray-700 mb-1">初始密码 <span class="text-red-500">*</span></label>
            <input
                type="password"
                v-model="currentUser.password"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"
                required
                placeholder="至少8个字符"
            >
          </div>

          <div>
            <label class="flex items-center">
              <input
                  type="checkbox"
                  v-model="currentUser.active"
                  class="rounded border-gray-300 text-emerald-600 shadow-sm focus:border-emerald-300 focus:ring focus:ring-emerald-200 focus:ring-opacity-50"
              >
              <span class="ml-2 text-sm text-gray-700">启用该用户</span>
            </label>
          </div>
        </div>

        <div class="flex justify-end space-x-3">
          <button type="button" @click="closeUserModal" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">取消</button>
          <button type="submit" class="px-4 py-2 bg-emerald-600 text-white rounded-md hover:bg-emerald-700">保存</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 重置密码弹窗 -->
  <div v-if="showResetPasswordModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-gray-800">重置密码</h3>
        <button @click="showResetPasswordModal = false" class="text-gray-400 hover:text-gray-500">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <p class="text-gray-600 mb-4">确定要重置用户 ID: <span class="font-medium">{{ selectedUserId }}</span> 的密码吗？重置后密码将变为默认密码 <span class="font-medium">123456</span>，用户下次登录需强制修改密码。</p>
      <div class="flex justify-end space-x-3">
        <button @click="showResetPasswordModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">取消</button>
        <button @click="confirmResetPassword" class="px-4 py-2 bg-emerald-600 text-white rounded-md hover:bg-emerald-700">确认重置</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 厂商数据（用于用户所属厂商选择）
const companies = ref([
  { id: 1, name: "绿色能源科技" },
  { id: 2, name: "蓝天制造集团" },
  { id: 3, name: "清新化工有限公司" },
  { id: 4, name: "环保建材集团" },
  { id: 5, name: "可持续农业发展" }
]);

// 用户数据
const users = ref([
  {
    id: 1,
    name: "张三",
    avatar: "https://picsum.photos/id/1012/40/40",
    email: "zhangsan@example.com",
    company: "绿色能源科技",
    role: "厂商管理员",
    regDate: "2023-01-15",
    lastLogin: "2025-09-07 09:30",
    active: true,
    password: ""
  },
  {
    id: 2,
    name: "李四",
    avatar: "https://picsum.photos/id/1013/40/40",
    email: "lisi@example.com",
    company: "",
    role: "普通用户",
    regDate: "2023-02-20",
    lastLogin: "2025-09-08 14:20",
    active: true,
    password: ""
  },
  {
    id: 3,
    name: "王五",
    avatar: "https://picsum.photos/id/1014/40/40",
    email: "wangwu@example.com",
    company: "蓝天制造集团",
    role: "厂商管理员",
    regDate: "2023-03-05",
    lastLogin: "2025-09-06 16:45",
    active: true,
    password: ""
  },
  {
    id: 4,
    name: "赵六",
    avatar: "https://picsum.photos/id/1015/40/40",
    email: "zhaoliu@example.com",
    company: "",
    role: "普通用户",
    regDate: "2023-04-18",
    lastLogin: "",
    active: false,
    password: ""
  },
  {
    id: 5,
    name: "系统管理员",
    avatar: "https://picsum.photos/id/1016/40/40",
    email: "admin@example.com",
    company: "",
    role: "超级管理员",
    regDate: "2023-01-01",
    lastLogin: "2025-09-08 10:15",
    active: true,
    password: ""
  }
]);

// 筛选条件
const searchKeyword = ref('');
const selectedRole = ref('');
const selectedStatus = ref('');

// 筛选用户
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    // 搜索关键词筛选
    const matchesSearch = user.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        user.email.toLowerCase().includes(searchKeyword.value.toLowerCase());

    // 角色筛选
    const matchesRole = !selectedRole.value || user.role === selectedRole.value;

    // 状态筛选
    const matchesStatus = !selectedStatus.value ||
        (selectedStatus.value === 'active' && user.active) ||
        (selectedStatus.value === 'inactive' && !user.active);

    return matchesSearch && matchesRole && matchesStatus;
  });
});

// 筛选用户方法（用于select变化时触发）
const filterUsers = () => {
  // 计算属性会自动更新，这里只是触发重绘
};

// 用户弹窗相关
const showUserModal = ref(false);
const isEditing = ref(false);
const currentUser = ref({
  id: null,
  name: '',
  avatar: 'https://picsum.photos/id/1005/40/40',
  email: '',
  company: '',
  role: '',
  regDate: new Date().toISOString().split('T')[0],
  lastLogin: '',
  active: true,
  password: ''
});

// 打开新增用户弹窗
const openAddUserModal = () => {
  isEditing.value = false;
  currentUser.value = {
    id: Date.now(),
    name: '',
    avatar: 'https://picsum.photos/id/1005/40/40',
    email: '',
    company: '',
    role: '',
    regDate: new Date().toISOString().split('T')[0],
    lastLogin: '',
    active: true,
    password: ''
  };
  showUserModal.value = true;
};

// 打开编辑用户弹窗
const openEditUserModal = (user) => {
  isEditing.value = true;
  currentUser.value = JSON.parse(JSON.stringify(user));
  showUserModal.value = true;
};

// 关闭用户弹窗
const closeUserModal = () => {
  showUserModal.value = false;
};

// 保存用户信息
const saveUser = () => {
  if (isEditing.value) {
    // 编辑现有用户
    const index = users.value.findIndex(u => u.id === currentUser.value.id);
    if (index !== -1) {
      users.value[index] = currentUser.value;
    }
  } else {
    // 添加新用户
    users.value.push(currentUser.value);
  }
  showUserModal.value = false;
  alert(isEditing.value ? '用户信息已更新' : '新用户已添加，初始密码已设置');
};

// 切换用户状态
const toggleUserStatus = (index) => {
  users.value[index].active = !users.value[index].active;
  alert(`用户已${users.value[index].active ? '启用' : '禁用'}`);
};

// 重置密码相关
const showResetPasswordModal = ref(false);
const selectedUserId = ref('');

const resetPassword = (userId) => {
  selectedUserId.value = userId;
  showResetPasswordModal.value = true;
};

const confirmResetPassword = () => {
  // 实际项目中需调用接口重置密码
  alert(`用户 ID: ${selectedUserId.value} 的密码已重置为默认密码 123456`);
  showResetPasswordModal.value = false;
};
</script>
